package com.freecat.xmqgct.mvp.ui.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.blankj.utilcode.util.SPUtils;
import com.freecat.xmqgct.R;
import com.freecat.xmqgct.mvp.model.entity.MapPointEntity;
import com.freecat.xmqgct.mvp.presenter.MainPresenter;
import com.freecat.xmqgct.utils.Constant;
import com.freecat.xmqgct.utils.MapFixUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.jessyan.art.base.BaseActivity;
import me.jessyan.art.mvp.IView;
import me.jessyan.art.mvp.Message;
import me.jessyan.art.utils.ArtUtils;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArtTemplate on 09/25/2019 17:56
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArt">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class MapActivity extends BaseActivity<MainPresenter> implements IView {

    @BindView(R.id.map_view)
    MapView mapView;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.btn_confirm)
    Button btn_confirm;
    private BaiduMap baiduMap;
    private GeoCoder geoCoder;
    private LatLng currentLocation;
    private String add;
    private LocationClient locationClient;
    double Apotlon;

    double Apotlat;

    private volatile boolean isFristLocation = true;


    int countx=1;

    LatLng AlatLng = null;
    MarkerOptions markerOptions1=null;

//    List<LatLng> points = new ArrayList<LatLng>();
    List<MapPointEntity> points = new ArrayList<MapPointEntity>();

    LocationClientOption locationOption = new LocationClientOption();

    private List<OverlayOptions> overlayOptionses=new ArrayList<OverlayOptions>();
    private MarkerOptions options;


//    HashMap<String,LatLng> LatLnglist=new  HashMap<String,LatLng>();

    ArrayList<LatLng> LatLnglist=new ArrayList<LatLng>();

    boolean isFirstLoc=true;
    String zkwzjl;

    double lon;
    double lat;

    double endlon;
    double endlat;
    String Olon;
    String Olat;
    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_map; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        setTitle("选择位置");
        //初始化，获取提交的精维度坐标
        //
        ReverseGeoCodeOption op = new ReverseGeoCodeOption();
        MapPointEntity mpe=new MapPointEntity();

        zkwzjl = SPUtils.getInstance(Constant.SP_CONFIG).getString(Constant.ZKWZJLCS);



        //初始化数据
//        LatLng latLng = new LatLng(lat, lon);
//
//        op.location(latLng);
        initLocationOption();
        baiduMap = mapView.getMap();




//        updateView(latLng2);

//         updateView2(points);
//        setListener();

//        geoCoder = GeoCoder.newInstance();
//        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
//            @Override
//            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
//
//            }
//
//            @Override
//            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
//                add = reverseGeoCodeResult.getAddress();
//                if (tvAddress != null) {
//                    tvAddress.setText(add);
//                }
//                currentLocation = reverseGeoCodeResult.getLocation();
//            }
//        });
//
////
//        geoCoder.reverseGeoCode(op);


//          for (LatLng p : points) {
//              BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.marker);
//              MarkerOptions markerOptions = new MarkerOptions().position(p).draggable(true)
//                      .icon(bitmapDescriptor) .zIndex(10).period(10).animateType(MarkerOptions.MarkerAnimateType.grow);;
//              overlayOptionses.add(markerOptions);
//
//        }


        //图层，确定当前坐标和基准坐标位置，并显示直线距离.
//        baiduMap.addOverlays(overlayOptionses);

//        LatLngBounds.Builder builder = new LatLngBounds.Builder();

//        points.add(latLng);
//        for (LatLng p : points) {
//            builder = builder.include(p);
//        }

//        for (MPoint point : pointCollection) {
//
//            double mLatitude = point.getLatitude();
//            double mLongitude = point.getLongitude();
//
//            LatLng mPoint = new LatLng(mLatitude, mLongitude);
//
//            MarkerOptions oA = new MarkerOptions().position(mPoint).icon(bdA);
//            overlayOptions.add(oA);
//
//        }
//        LatLngBounds latlngBounds = builder.build();
//        MapStatusUpdate u =MapStatusUpdateFactory.newLatLngBounds(latlngBounds);
//
//        baiduMap.setMapStatus(u);
//        baiduMap.animateMapStatus(u);
//        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(latLng, 20);
//
//        baiduMap.animateMapStatus(mapStatusUpdate);
    }


    private void setListener() {
        baiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                baiduMap.clear();
                BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.marker);
                MarkerOptions markerOptions = new MarkerOptions().position(latLng).draggable(true)
                        .icon(bitmapDescriptor);
                baiduMap.addOverlay(markerOptions);
                ReverseGeoCodeOption op = new ReverseGeoCodeOption();
                op.location(latLng);
                geoCoder.reverseGeoCode(op);
            }

            @Override
            public void onMapPoiClick(MapPoi mapPoi) {

            }
        });
        baiduMap.setOnMarkerDragListener(new BaiduMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDrag(Marker marker) {

            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                ReverseGeoCodeOption op = new ReverseGeoCodeOption();
                op.location(marker.getPosition());
                geoCoder.reverseGeoCode(op);
            }

            @Override
            public void onMarkerDragStart(Marker marker) {

            }
        });
    }

    @Override
    @Nullable
    public MainPresenter obtainPresenter() {
        return new MainPresenter(ArtUtils.obtainAppComponentFromContext(this));
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        mapView.onDestroy();
        super.onDestroy();
    }
    private void initLocationOption() {
        locationClient = new LocationClient(getApplicationContext());
//声明LocationClient类实例并配置定位参数
//        LocationClientOption locationOption = new LocationClientOption();
        MyLocationListener myLocationListener = new MyLocationListener();
//注册监听函数
        locationClient.registerLocationListener(myLocationListener);
        locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
//        locationOption.setCoorType("bd09ll");
        //可选，默认false，设置是否开启Gps定位
        locationOption.setOpenGps(true);
//可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        locationOption.setScanSpan(3000);
//可选，设置是否需要地址信息，默认不需要
        locationOption.setIsNeedAddress(true);
//可选，设置是否需要地址描述
        locationOption.setIsNeedLocationDescribe(false);
//可选，设置是否需要设备方向结果
        locationOption.setNeedDeviceDirect(true);
//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        locationOption.setLocationNotify(false);
//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        locationOption.setIgnoreKillProcess(true);
//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        locationOption.setIsNeedLocationPoiList(true);
//可选，默认false，设置是否收集CRASH信息，默认收集
        locationOption.SetIgnoreCacheException(false);
//可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
        locationOption.setIsNeedAltitude(true);
//设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
        locationOption.setOpenAutoNotifyMode();
////设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
//        locationOption.setOpenAutoNotifyMode(1000,10, LocationClientOption.LOC_SENSITIVITY_HIGHT);
        locationClient.setLocOption(locationOption);
        locationClient.start();
    }

    @OnClick(R.id.btn_confirm)
    public void onViewClicked() {


        /*
        *
        *
        * */
            points.clear();
            baiduMap.clear();//先清除图层

            if (String.valueOf(lon)!=null&&String.valueOf(lat)!=null&&String.valueOf(lon).length()>6&&String.valueOf(lat).length()>6){

                MapPointEntity MPE1=new MapPointEntity();
                MPE1.setPointName("基准开孔点");
                MPE1.setPointLat(lat);
                MPE1.setPointLon(lon);
                System.out.println("Apotlon===="+Apotlon+"Apotlat===="+Apotlat);

                points.add(MPE1);

            }
            if (String.valueOf(endlat)!=null&&String.valueOf(endlon)!=null&&String.valueOf(endlat).length()>6&&String.valueOf(endlon).length()>6){
                MapPointEntity MPE2=new MapPointEntity();
                MPE2.setPointName("开孔结束点");
                MPE2.setPointLat(endlat);
                MPE2.setPointLon(endlon);
                points.add(MPE2);
            }


          LatLng ll = new LatLng(Apotlat, Apotlon);
//        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
//        baiduMap.animateMapStatus(u);
//        generateMarker(points);
          MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
          baiduMap.animateMapStatus(u);
          generateMarker(points);
    }


    /**
     * 实现定位回调
     */
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {


            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
//            baiduMap.clear();
//            //获取纬度信息

            HashMap marsTobaidu= MapFixUtil.marsTobaidu(location.getLongitude(),location.getLatitude());
            Apotlon = (double) marsTobaidu.get("baidu_point_lon");
            Apotlat= (double) marsTobaidu.get("baidu_point_lat");
//            Toast.makeText(MapActivity.this,"Apotlat0"+Apotlat+"__"+Apotlat, Toast.LENGTH_SHORT).show();
//           LatLng latLng = new LatLng(latitude, longitude);
//            LatLng latLng = new LatLng(latitude1, longitude1);
//            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.marker);
//            MarkerOptions markerOptions = new MarkerOptions().position(latLng).draggable(true)
//                    .icon(bitmapDescriptor);
//            baiduMap.addOverlay(markerOptions);
//            ReverseGeoCodeOption op = new ReverseGeoCodeOption();
//            op.location(latLng);
//            geoCoder.reverseGeoCode(op);
//            MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(latLng, 15);
//            baiduMap.animateMapStatus(mapStatusUpdate);
//            locationClient.stop();

            if (countx<=1){
                if (Apotlat>0&&Apotlon>0){
                    MapPointEntity MPE2=new MapPointEntity();
                    MPE2.setPointName("当前坐标点");
                    MPE2.setPointLat(Apotlat);
                    MPE2.setPointLon(Apotlon);
                    points.add(MPE2);
                }
                if (location == null || mapView == null){
                    return;
                }
                MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(100).latitude(Apotlat).longitude(Apotlon).build();
                baiduMap.setMyLocationData(locData);
                LatLng ll = new LatLng(Apotlat, Apotlon);
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                baiduMap.animateMapStatus(u);
                generateMarker(points);
            }

//            countx++;


//            LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
//            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())// 构造定位数据
//                    // 此处设置开发者获取到的方向信息，顺时针0-360
//                    .direction(100).latitude(location.getLatitude())
//                    .longitude(location.getLongitude()).build();
//            baiduMap.setMyLocationData(locData);// 设置定位数据
//            if (isFirstLoc) {
//                isFirstLoc = false;
//                MapStatus.Builder builder = new MapStatus.Builder();
//                builder.zoom(28.0f).target(latLng);
//                baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
//
//                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
//                    Toast.makeText(MapActivity.this,location.getAddrStr(), Toast.LENGTH_SHORT).show();
////                    Log.d("TypeGpsLocation location", location.toString());
//                }else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
//                    Toast.makeText(MapActivity.this,location.getAddrStr(), Toast.LENGTH_SHORT).show();
//                }else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
//                    Toast.makeText(MapActivity.this,location.getAddrStr(), Toast.LENGTH_SHORT).show();
//                } else if (location.getLocType() == BDLocation.TypeServerError) {
//                    Toast.makeText(MapActivity.this, "服务器错误，请检查",Toast.LENGTH_SHORT).show();
//                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
//                    Toast.makeText(MapActivity.this, "网络错误，请检查",Toast.LENGTH_SHORT).show();
//                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
//                    Toast.makeText(MapActivity.this,"仪器模式错误，请检查是否飞行", Toast.LENGTH_SHORT).show();
//                }
//            }
//            updateView(latLng);//更新自定义标记显示
//            locationClient.stop();
        }
    }

    private void updateView(LatLng latLng) {
        baiduMap.clear();//先清除图层
        LatLng point = latLng;

        if (point != null) {
            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.marker);//构建Marker图标
            options = new MarkerOptions().position(point).icon(bitmap);// 构建MarkerOption，用于在地图上添加Marker
            overlayOptionses.add(options);
            baiduMap.addOverlays(overlayOptionses);// 在地图上添加Marker数组，并显示
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.zoom(28.0f).target(latLng);
            baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        } else {
            Toast.makeText(MapActivity.this,"没有获取到GPS坐标请检查", Toast.LENGTH_SHORT).show();
        }
    }




    public void generateMarker(List<MapPointEntity> ListPoint) {

//
//        Double lat1=Double.valueOf("29.58836605012687");
//        Double lot2=Double.valueOf("106.53594518736195");

//        LatLng nl=new LatLng(lat1,lot2);

//        ListPoint.add(nl);

             int x=0;
                 for (MapPointEntity point:ListPoint) {
                     x++;
                     System.out.println( "x"+x+"当前坐标"+point.getPointLat()+"__"+point.getPointLon());


//                         Hotel hotel = (Hotel) iterator.next();
//                         LatLng ll = new LatLng(point);
                         View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.baidumap_point_custom, null);
                         // ImageView img_hotel_image=
                         // (ImageView)view.findViewById(R.id.img_hotel_image);
                         // DownloadImageTask(img_hotel_image).execute(hotel.getHotelImageUrl());
                         TextView baidumap_custom_text = (TextView) view.findViewById(R.id.baidumap_custom_text);
                         baidumap_custom_text.setText(point.getPointName());
                         LatLng ll = new LatLng(point.getPointLat(),point.getPointLon());
                         BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromBitmap(getViewBitmap(view));
//                         String title="点";
//                         Bundle bundle = new Bundle();
//                         bundle.putSerializable("POT", title+x);

                         BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.marker);//构建Marker图标
                         OverlayOptions oo = new MarkerOptions().position(ll).icon(markerIcon).zIndex(9).draggable(true);
                         baiduMap.addOverlay(oo);
                         MapStatus.Builder builder = new MapStatus.Builder();
                         builder.zoom(15.0f).target(ll);
                         baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                         if (point.getPointName().equals("基准开孔点")){
                             OverlayOptions ooCircle = new CircleOptions().fillColor(0x384d73b3)
                                     .center(ll).stroke(new Stroke(3, 0x784d73b3))
                                     .radius(Integer.valueOf(zkwzjl));
                             baiduMap.addOverlay(ooCircle);
                         }

                     }

    }


    //自定义百度点位图
    private Bitmap getViewBitmap(View addViewContent) {

        addViewContent.setDrawingCacheEnabled(true);

        addViewContent.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0, addViewContent.getMeasuredWidth(), addViewContent.getMeasuredHeight());

        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        return bitmap;
    }



    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {

        ArtUtils.makeText(this, message);
    }

    @Override
    public void handleMessage(@NonNull Message message) {

        switch (message.what) {
            case 0:
                break;
            case 1:
                break;
        }
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
